/***
 * @Title:[MyBatisConfig.java]
 * @Package:[com.yixun.qfbao.mybatis]
 * @author:[shaoping.jiao]
 * @CreateDate:[2017 年11月8日 下午4:33:22]
 * @UpdateUser:[shaoping.jiao]
 * @UpdateDate:[2017 年11月8日 下午4:33:22]
 * @Description:[Mybatis基础配置]
 * @version:[V1.0]
 * */
package com.yixun.qfbao.mybatis;

import com.yixun.qfbao.druid.filter.config.SecurityDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;

/****
 * 
 * @ClassName :MyBatisConfig
 * @author :[shaoping.jiao]
 * @CreateDate :[2017 年11月8日 下午4:33:22]
 * @UpdateUser :[shaoping.jiao]
 * @UpdateDate :[2017 年11月8日 下午4:33:22]
 * @Description :[Mybatis基础配置]
 * @version :[V1.0]
 */
@Configuration
@EnableTransactionManagement
public class MyBatisConfig implements TransactionManagementConfigurer {
	
	private static final Logger logger = LoggerFactory.getLogger(MyBatisConfig.class);
	
	@Bean
	@ConfigurationProperties(prefix = "spring.datasource")
	public SecurityDataSource dataSource() {
		return new SecurityDataSource();
	}
	
	@Bean(name = "sqlSessionFactory")
	public SqlSessionFactory sqlSessionFactoryBean() {
		try {
			SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
			sqlSessionFactoryBean.setDataSource(dataSource());
			PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
			sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath*:com/yixun/qfbao/**/*.xml"));
			return sqlSessionFactoryBean.getObject();
		} catch (Exception e) {
			logger.error("sqlSessionFactoryBean Error: {}", e);
			throw new RuntimeException(e);
		}
	}
	
	@Bean
	public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
		return new SqlSessionTemplate(sqlSessionFactory);
	}
	
	@Override
	public PlatformTransactionManager annotationDrivenTransactionManager() {
		return new DataSourceTransactionManager(dataSource());
	}
	
}
